<template>
  <el-card>
    <el-form ref="form" :model="form">
      <el-form-item label="收件人邮箱">
        <el-input v-model="form.recipientEmail" placeholder="请输入收件人邮箱"></el-input>
      </el-form-item>
      <el-form-item label="标题">
        <el-input v-model="form.subject" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="内容">
        <el-input v-model="form.body" type="textarea" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item label="文件">
        <el-upload action="#" :on-change="handleFileChange" :auto-upload="false" :limit="1">
          <el-button type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="sendEmail">发送</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { emailSendEmail, emailsendEmail } from "@/api/EmailDialog";

export default {
  data() {
    return {
      form: {
        recipientEmail: "",
        subject: "",
        body: "",
        file: null,  // 用于存储上传的文件
      },
    };
  },
  methods: {
    reset() {
      this.form = {
        recipientEmail: "",
        subject: "",
        body: "",
        file: null,
      };
      this.resetForm("form");
    },
    handleFileChange(file) {
      this.form.file = file.raw;  // 保存上传的文件
    },
    async sendEmail() {
      const { recipientEmail, subject, body, file } = this.form;

      if (file) {
        // 如果有文件，调用 emailsendEmail API
        const formData = new FormData();
        formData.append("recipientEmail", recipientEmail);
        formData.append("subject", subject);
        formData.append("body", body);
        formData.append("file", file);

        try {
          await emailsendEmail(formData);
          this.$message.success("邮件发送成功");
          this.reset()
        } catch (error) {
          this.$message.error("邮件发送失败");
        }
      } else {
        // 如果没有文件，调用 emailSendEmail API
        try {
          await emailSendEmail({ recipientEmail, subject, body });
          this.$message.success("邮件发送成功");
          this.reset()
        } catch (error) {
          this.$message.error("邮件发送失败");
        }
      }
    },
  },
};
</script>

<style scoped>
.el-card {
  margin: 0 auto;
  padding: 20px;
}
</style>